<template>
  <div class="container">
    <header>
      <h1>指标数据管理面板</h1>
      <p>按分类组织的指标数据，支持分组折叠、搜索和统计分析</p>
    </header>
    
    <div class="controls">
      <div class="search-box">
        <input type="text" v-model="searchQuery" placeholder="搜索指标名称、位置或代码...">
      </div>
      <div class="feature-controls">
        <div class="feature-select">
          <label for="feature-select">目标区域：</label>
          <select 
            id="feature-select"
            v-model="currentFeature"
            class="custom-select"
          >
            <option value="" disabled selected>请选择目标区域</option>
            <option 
              v-for="feature in features" 
              :value="feature" 
              :key="feature.extData.id" 
            >
              {{ feature.extData.name  }}
            </option>
          </select>
          <button 
          class="custom-button"
          @click="geAllRouter"
          :disabled="!currentFeature"
        >
          开始导航 
        </button>
        </div>
        
      </div>
      <div class="stats-bar">
        <div class="stat-card">
          <div class="value">{{ totalItems }}</div>
          <div class="label">总指标数</div>
        </div>
        <div class="stat-card">
          <div class="value">{{ categories }}</div>
          <div class="label">分类数</div>
        </div>
        <div class="stat-card">
          <div class="value">{{ uniqueGroups }}</div>
          <div class="label">分组数</div>
        </div>
      </div>
    </div>
    
    <div class="content">
      <div class="custom-table">
        <!-- 第一级分组：按顶层分类 -->
        <div 
          v-for="(category, catIndex) in filteredData" 
          :key="category.name"
          class="category-group"
        >
          <h3 
            @click="toggleCategoryCollapse(catIndex)" 
            :class="{ collapsed: categoryCollapses[catIndex] }"
          >
            <i :class="categoryCollapses[catIndex] ? 'el-icon-arrow-right' : 'el-icon-arrow-down'"></i>
            {{ category.name }}
          </h3>
  
          <div v-show="!categoryCollapses[catIndex]">
            <!-- 第二级分组：按indexName -->
            <div 
              v-for="(group, groupIndex) in category.groups" 
              :key="group.indexName"
              class="index-group"
            >
              <div 
                class="group-header"
                :class="{ collapsed: groupCollapses[getGroupKey(catIndex, groupIndex)] }"
                @click="toggleGroupCollapse(catIndex, groupIndex)"
              >
                <span class="group-title">
                  <i :class="groupCollapses[getGroupKey(catIndex, groupIndex)] ? 'el-icon-arrow-right' : 'el-icon-arrow-down'"></i>
                  {{ group.indexName }}
                </span>
                <span class="group-stats">(共 {{ group.items.length }} 项)</span>
                
                <div class="stats-container">
                  <div class="stat-item">
                    <span class="stat-value">{{ calculateSum(group.items) }}</span>
                    <span class="stat-label">总和</span>
                  </div>
                  <div class="stat-item">
                    <span class="stat-value">{{ calculateUniqueDepartments(group.items) }}</span>
                    <span class="stat-label">单位数量</span>
                  </div>
                  <div class="stat-item">
                    <span class="stat-value">{{ calculateMin(group.items) }}</span>
                    <span class="stat-label">最小值</span>
                  </div>
                  <div class="stat-item">
                    <span class="stat-value">{{ calculateMax(group.items) }}</span>
                    <span class="stat-label">最大值</span>
                  </div>
                </div>
              </div>
              
              <div v-show="!groupCollapses[getGroupKey(catIndex, groupIndex)]">
                <!-- 数据表格 -->
                <table class="data-table">
                  <thead>
                    <tr>
                      <!-- 添加选择列 -->
                      <th class="col-select">
                        <input 
                          type="checkbox" 
                          :checked="isGroupAllSelected(catIndex, groupIndex)"
                          @change="toggleGroupSelection(catIndex, groupIndex, $event)"
                        >
                      </th>
                      <th class="col-name">指标名称</th>
                      <th class="col-value">指标值</th>
                      <th class="col-code">单位</th>
                      <th class="col-location">位置</th>
                      <th class="col-actions">操作</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr 
                      v-for="(item, idx) in group.items" 
                      :key="idx"
                    >
                     <td class="col-select">
                        <input 
                          type="checkbox" 
                          v-model="item.selected"
                      >
                      </td>
                      <td 
                        class="col-name"
                        :title="item.name"
                      >{{ truncateText(item.name, 20) }}</td>
                      <td class="col-value">{{ formatValue(item.value) }}</td>
                      <td 
                        class="col-code"
                        :title="item.departName"
                      >{{ truncateText(item.departName, 10) }}</td>
                      <td 
                        class="col-location"
                        @click="toLocation(item.location)"
                        :title="formatLocation(item.location)"
                      >
                        <span class="location-pin">📍</span>
                        {{ truncateText(formatLocation(item.location), 25) }}
                      </td>
                      <td class="col-actions">
                        <div class="actions-container">
                          <button @click="getRouter(item)">路径</button>
                        </div>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <div class="footer">
      <p>共显示 <span class="highlight">{{ filteredItemCount }}</span> 个指标 | 最后更新时间: {{ currentDate }}</p>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Prop } from 'vue-property-decorator';
import { Getter } from 'vuex-class';

interface GroupedItem {
  indexName: string;
  items: any[];
}

interface ProcessedData {
  name: string;
  groups: GroupedItem[];
}

@Component
export default class NativeGroupTable extends Vue {
  @Prop({ required: true }) readonly data!: any[];
  @Getter features!: any[];
  private searchQuery = '';

  private currentFeature = null;
  
  // 使用两个对象分别存储分类和分组的折叠状态
  private categoryCollapses: Record<number, boolean> = {};
  private groupCollapses: Record<string, boolean> = {};

  /**
   * 获取处理后的数据
   */
  get processedData(): ProcessedData[] {
    return this.data.map((category, index) => ({
      name: category.name,
      groups: this.groupByIndexName(category.data, index)
    }));
  }

  // 生成分组唯一键
  private getGroupKey(catIndex: number, groupIndex: number): string {
    return `${catIndex}-${groupIndex}`;
  }

  // 分组数据
  private groupByIndexName(items: any[], catIndex: number): GroupedItem[] {
    const groups = items.reduce((acc, current) => {
      const key = current.indexName;
      if (!acc[key]) {
        acc[key] = {
          indexName: key,
          items: []
        };
      }
       // 初始化选中状态
      if (current.selected === undefined) {
        this.$set(current, 'selected', false);
      }
      acc[key].items.push(current);
      return acc;
    }, {} as Record<string, GroupedItem>);
    return Object.values(groups);
  }


  // 判断分组是否全选
  isGroupAllSelected(catIndex: number, groupIndex: number): boolean {
    const group = this.filteredData[catIndex]?.groups[groupIndex];
    if (!group || group.items.length === 0) return false;
    return group.items.every(item => item.selected);
  }

  geAllRouter(){
    this.filteredData.forEach(category => {
      category.groups.forEach(group => {
        group.items.forEach(item => {
          if(item.selected === true){
              this.getRouter(item);
          }
        });
      });
    });
  }
  // 切换分组全选状态
  toggleGroupSelection(catIndex: number, groupIndex: number, event: Event) {
    const checked = (event.target as HTMLInputElement).checked;
    const group = this.filteredData[catIndex]?.groups[groupIndex];
    if (group) {
      group.items.forEach(item => {
        item.selected = checked;
      });
    }
  }
  // 切换分类折叠状态
  toggleCategoryCollapse(index: number) {
    this.$set(this.categoryCollapses, index, !this.categoryCollapses[index]);
  }

  // 切换分组折叠状态
  toggleGroupCollapse(catIndex: number, groupIndex: number) {
    const groupKey = this.getGroupKey(catIndex, groupIndex);
    this.$set(this.groupCollapses, groupKey, !this.groupCollapses[groupKey]);
  }

  get filteredItemCount() {
    return this.totalItems;
  }

  get currentDate() {
    return new Date().toLocaleDateString('zh-CN', { 
      year: 'numeric', 
      month: 'long', 
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
  }

  get filteredData() {
    if (!this.searchQuery) return this.processedData; 
  
    const query = this.searchQuery.toLowerCase(); 
    return this.processedData.map((category, catIndex) => {
      const groups = category.groups.map((group, groupIndex) => {
        const items = group.items.filter(item => 
          item.name.toLowerCase().includes(query) ||
          (item.departName && item.departName.toLowerCase().includes(query)) ||
          (item.location && item.location.toLowerCase().includes(query)) 
        );
        return {
          ...group,
          items
        };
      }).filter(group => group.items.length > 0);
      
      return { ...category, groups };
    }).filter(category => category.groups.length > 0);
  }

  get totalItems() {
    return this.filteredData.reduce((total, category) => {
      return total + category.groups.reduce((sum, group) => sum + group.items.length, 0);
    }, 0);
  }

  get uniqueGroups() {
    return this.filteredData.reduce((total, category) => total + category.groups.length, 0);
  }

  get categories() {
    return this.filteredData.length;
  }

  // 文本截断方法
  truncateText(text: string, maxLength: number): string {
    if (!text) return '';
    return text.length > maxLength ? text.substring(0, maxLength) + '...' : text;
  }

  calculateMin(items: any[]): string {
    const values = items.map(item => parseFloat(item.value)).filter(n => !isNaN(n));
    return values.length ? Math.min(...values).toLocaleString(undefined, { maximumFractionDigits: 2 }) : '-';
  }

  calculateMax(items: any[]): string {
    const values = items.map(item => parseFloat(item.value)).filter(n => !isNaN(n));
    return values.length ? Math.max(...values).toLocaleString(undefined, { maximumFractionDigits: 2 }) : '-';
  }

  formatValue(value: string): string {
    const num = parseFloat(value);
    return isNaN(num) ? value : num.toLocaleString();
  }

  calculateSum(items: any[]): string {
    const sum = items.reduce((acc, cur) => {
      const num = parseFloat(cur.value);
      return acc + (isNaN(num) ? 0 : num);
    }, 0);
    return sum.toLocaleString(undefined, { maximumFractionDigits: 2 });
  }

  changeSelect(val: any): void {
    console.log(val);
  }

  calculateAverage(items: any[]): string {
    const sum = items.reduce((acc, cur) => {
      const num = parseFloat(cur.value);
      return acc + (isNaN(num) ? 0 : num);
    }, 0);
    return (sum / items.length).toLocaleString(undefined, { 
      maximumFractionDigits: 2 
    });
  }

  calculateUniqueDepartments(items: any[]): number {

    const deparments = items.map(item => item.departName).filter(Boolean); // 过滤掉空值

    const uniqueSet = new Set(deparments);

    return uniqueSet.size;

}

  toLocation(location: string): void {
    (this as any).$bus.$emit('toLocation', location);
  }

  formatLocation(location: string): string {
    if (!location) return '未知';
    return location.split(',').map(Number.parseFloat).map(v => v.toFixed(6)).join(', ');
  }

  getRouter(item: any): void {
    if(!this.currentFeature){
      this.$message.error('请先选择目标地址');
      return;
    }
    item.feature = this.currentFeature;
    (this as any).$bus.$emit('getRouter', item);
  }
  
  mounted() {
    // 默认展开所有分类和分组
    this.data.forEach((_, index) => {
      this.$set(this.categoryCollapses, index, false);
    });
    
    // 初始化分组折叠状态
    this.processedData.forEach((category, catIndex) => {
      category.groups.forEach((group, groupIndex) => {
        const groupKey = this.getGroupKey(catIndex, groupIndex);
        
        this.$set(this.groupCollapses, groupKey, false);
      });
    });

    
    // 初始化分组折叠状态
    this.processedData.forEach((category, catIndex) => {
      category.groups.forEach((_, groupIndex) => {
        const groupKey = this.getGroupKey(catIndex, groupIndex);
        this.$set(this.groupCollapses, groupKey, true);
      });
    });
  
  }
}
</script>

<style scoped>
.container {
  max-width: 1200px;
  margin: 0px;
  background: white;
  border-radius: 2px;
  width:100%;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
}

header {
  background: linear-gradient(135deg, #3498db, #2c3e50);
  color: white;
  padding: 6px 10px;
  text-align: center;
}

header h1 {
  font-size: 14px;
  margin-bottom: 6px;
  font-weight: 600;
}

header p {
  font-size: 12px;
  opacity: 0.9;
  max-width: 700px;
  margin: 0 auto;
}

.controls {
  display: flex;

  justify-content: space-between;
  padding:5px;
  background: #f8fafc;
  border-bottom: 1px solid #eaeef5;
  flex-wrap: wrap;
  gap: 15px;
}



.search-box {
  position: relative;
  min-width: 100px;
  width: 100%;
}

.search-box input {
  width: calc(100% - 50px);
  padding: 10px 10px 10px 40px;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 14px;
  transition: all 0.3s;
   background: white;
   box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.search-box input:focus {
  outline: none;
  border-color: #3498db;
  box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.2);
}

.stats-bar {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.stat-card {
  background: white;
  border-radius: 8px;
  padding: 8px 16px;
  min-width: 80px;
  text-align: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  border: 1px solid #eee;
}

.stat-card .value {
  font-size: 16px;
  font-weight: 700;
  color: #2c3e50;
  line-height: 1.2;
}

.stat-card .label {
  font-size: 12px;
  color: #7f8c8d;
  margin-top: 2px;
}

.content {
  padding: 0px;
}

.custom-table {
  border-radius: 2px;
  overflow: hidden;
}

.category-group {
  margin-bottom: 2px;
  border: 1px solid #e1e8ed;
  border-radius: 2px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.03);
  background: white;
  transition: all 0.3s;
}

.category-group:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

h3 {
  padding: 12px 20px;
  margin: 0;
  background: linear-gradient(120deg, #f0f7ff, #e1ecf7);
  border-bottom: 1px solid #d4e3f7;
  color: #2c3e50;
  font-size: 12px;
  display: flex;
  align-items: center;
  cursor: pointer;
  transition: background 0.3s;
  user-select: none;
}

h3:hover {
  background: linear-gradient(120deg, #e1ecf7, #d4e3f7);
}

h3 i {
  margin-right: 12px;
  font-size: 11px;
  transition: transform 0.3s ease;
  width: 16px;
  text-align: center;
}

.index-group {
  margin: 0;
  border-bottom: 1px solid #f0f4f8;
  transition: background 0.3s;
}

.index-group:last-child {
  border-bottom: none;
}

.group-header {
  padding: 12px 20px;
  background-color: #f8fafd;
  display: flex;
  align-items: center;
  cursor: pointer;
  transition: background 0.2s;
  user-select: none;
}

.group-header:hover {
  background-color: #f0f5fc;
}

.group-title {
  font-size: 11px;
  font-weight: 600;
  color: #34495e;
  display: flex;
  align-items: center;
  flex: 1;
}

.group-title i {
  margin-right: 5px;
  font-size: 11px;
  color: #3498db;
  transition: transform 0.3s ease;
  width: 14px;
  text-align: center;
}

.group-header.collapsed .group-title i {
  transform: rotate(-90deg);
}

.group-stats {
  margin-left: 5px;
  font-size: 12px;
  color: #7f8c8d;
  white-space: nowrap;
}

.stats-container {
  margin-left: auto;
  display: flex;
  gap: 5px;
  flex-wrap: wrap;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  min-width: 60px;
}

.stat-value {
  font-size: 12px;
  font-weight: 700;
  color: #2980b9;
  white-space: nowrap;
}

.stat-label {
  font-size: 11px;
  color: #7f8c8d;
  margin-top: 2px;
  white-space: nowrap;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  background-color: white;
  table-layout: fixed;
}

.data-table th {
  padding: 10px 12px;
  background-color: #f8fafd;
  text-align: left;
  font-weight: 600;
  color: #2c3e50;
  border-bottom: 2px solid #eaeef5;
  font-size: 11px;
}

.data-table td {
  padding: 10px 12px;
  border-top: 1px solid #f0f4f8;
  color: #2d3436;
  font-size: 10px;
  vertical-align: middle;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.data-table tr:hover {
  background-color: #f8fbfe;
}

.col-select {
  width: 30px;
  text-align: center;
}

.col-name { 
  width:15%; 
}

.col-value { 
  width: 8%; 
  text-align: right;
  font-weight: 600;
  color: #2980b9;
}

.col-code { 
  width: 20%; 
}

.col-location { 
  width: 10%; 
  cursor: pointer;
  transition: color 0.2s;
}

.col-location:hover {
  color: #e74c3c;
}

.col-actions { 
  width: 15%; 
}

.location-pin {
  margin-right: 6px;
  vertical-align: middle;
  color: #e74c3c;
  font-size: 12px;
}

.actions-container {
  display: flex;
  gap: 6px;
}

.actions-container select {
  flex: 1;
  padding: 6px 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background-color: white;
  font-size: 12px;
  transition: all 0.2s;
  min-width: 80px;
}

.actions-container select:focus {
  outline: none;
  border-color: #3498db;
  box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.2);
}

.actions-container button {
  padding: 6px 12px;
  background: linear-gradient(to right, #3498db, #2980b9);
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
  font-size: 12px;
  font-weight: 500;
  white-space: nowrap;
}

.actions-container button:hover {
  background: linear-gradient(to right, #2980b9, #2573a7);
  transform: translateY(-1px);
  box-shadow: 0 2px 6px rgba(52, 152, 219, 0.3);
}

.footer {
  padding: 15px 20px;
  text-align: center;
  color: #7f8c8d;
  font-size: 13px;
  border-top: 1px solid #eee;
  background: #f8fafc;
}

.highlight {
  color: #3498db;
  font-weight: 600;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .controls {
    flex-direction: column;
    gap: 12px;
  }
  
  .search-box {
    width: 100%;
    max-width: none;
  }
  
  .stats-bar {
    width: 100%;
    justify-content: space-between;
  }
  
  .stat-card {
    flex: 1;
    min-width: 0;
    padding: 8px 10px;
  }
  
  .group-header {
    flex-wrap: wrap;
  }
  
  .stats-container {
    width: 100%;
    margin-top: 8px;
    justify-content: space-between;
    gap: 10px;
  }
  
  .stat-item {
    min-width: 0;
    flex: 1;
  }
  
  .col-name { 
    width: 25%; 
  }
  
  .col-value { 
    width: 15%; 
  }
  
  .col-code { 
    width: 25%; 
  }
  
  .col-location { 
    width: 20%; 
  }
  
  .col-actions { 
    width: 15%; 
  }
  
  .actions-container {
    flex-direction: column;
    gap: 5px;
  }
  
  .actions-container select, 
  .actions-container button {
    width: 100%;
  }
}

@media (max-width: 480px) {
  .data-table {
    display: block;
    overflow-x: auto;
  }
  
  .col-name { 
    width: 35%; 
  }
  
  .col-value { 
    width: 20%; 
  }
  
  .col-code { 
    width: 20%; 
  }
  
  .col-location { 
    width: 25%; 
  }
  
  .col-actions { 
    width: 20%; 
  }
}

.collapse-transition {
  transition: all 0.3s ease;
}

.feature-select {
  display: flex;
  align-items: center;
}
 
.feature-select label {
  font-size: 13px;
  color: #606266;
  margin-right: 8px;
  font-weight: 500;
  white-space: nowrap;
}


 
/* 调整Element UI组件样式 */
.el-select {
  margin-right: 10px;
}
 
.el-button {
  margin-left: 0;
}

.custom-select {
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #fff;
  color: #606266;
  font-size: 13px;
  transition: border-color 0.2s;
  margin-right: 10px;
  min-width: 100px;
  width: 60%;
}
 
.custom-select:focus {
  outline: none;
  border-color: #409eff;
}
 
.custom-button {
  padding: 8px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  transition: all 0.2s;
}
 
.custom-button:hover {
  background-color: #66b1ff;
}
 
.custom-button:disabled {
  background-color: #c0c4cc;
  cursor: not-allowed;
} 

.feature-controls {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-left: 0px;
  width: 100%;
  flex-wrap: wrap;
}
</style>